package com.flowplan.websocket.config;

import com.flowplan.auth.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.lang.NonNull;

/**
 * WebSocket配置类
 * 
 * @author FlowPlan Team
 */
@Slf4j
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 配置消息代理
     */
    @Override
    public void configureMessageBroker(@NonNull MessageBrokerRegistry config) {
        // 创建任务调度器
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(Runtime.getRuntime().availableProcessors() * 2);
        taskScheduler.setThreadNamePrefix("websocket-broker-");
        taskScheduler.initialize();
        
        // 启用简单消息代理
        config.enableSimpleBroker("/topic", "/queue")
              .setTaskScheduler(taskScheduler);

        // 设置应用程序前缀
        config.setApplicationDestinationPrefixes("/app");
        
        // 设置用户目的地前缀
        config.setUserDestinationPrefix("/user");
    }

    /**
     * 注册STOMP端点
     * 支持SockJS降级处理
     */
    @Override
    public void registerStompEndpoints(@NonNull StompEndpointRegistry registry) {
        // 创建任务调度器
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
        taskScheduler.setThreadNamePrefix("websocket-endpoint-");
        taskScheduler.initialize();
        
        registry.addEndpoint("/ws/collaboration")
                .setAllowedOriginPatterns("*")
                .withSockJS()
                .setTaskScheduler(taskScheduler);
    }

    /**
     * 配置客户端入站通道
     * 添加JWT认证拦截器
     */
    @Override
    public void configureClientInboundChannel(@NonNull ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(@NonNull Message<?> message, @NonNull MessageChannel channel) {
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                
                // 添加空值检查以防止潜在的空指针异常
                if (accessor == null) {
                    log.warn("无法从消息中提取StompHeaderAccessor");
                    return message;
                }
                
                if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                    // 提取JWT Token进行认证
                    String token = accessor.getFirstNativeHeader("Authorization");
                    if (token != null && token.startsWith("Bearer ")) {
                        token = token.substring(7);
                        try {
                            // 验证Token
                            String username = jwtTokenUtil.getUsernameFromToken(token);
                            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                            if (jwtTokenUtil.validateToken(token, userDetails)) {
                                UsernamePasswordAuthenticationToken authToken = 
                                    new UsernamePasswordAuthenticationToken(
                                        userDetails, null, userDetails.getAuthorities());
                                
                                SecurityContextHolder.getContext().setAuthentication(authToken);
                                accessor.setUser(authToken);
                                
                                log.info("WebSocket用户认证成功: {}", username);
                            } else {
                                log.warn("WebSocket认证失败: Token无效");
                                return null;
                            }
                        } catch (Exception e) {
                            log.error("WebSocket认证异常: {}", e.getMessage());
                            return null;
                        }
                    } else {
                        log.warn("WebSocket认证失败: 缺少Authorization头");
                        return null;
                    }
                }
                
                return message;
            }
        });
    }
}